import com.google.gson.Gson;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class Dictionary {


    static String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36";
    static String cookie = "_ga=GA1.3.53211268.1558696981; beta-redesign=active; gig_hasGmid=ver2; pl_did=c8f6f1c4-954a-4a51-b304-1aad8e227148; _fbp=fb.1.1562126413068.1454824175; _gig_llp=googleplus; _gig_llu=sean; logged=logged; notifications=cookiewarning%3BrenameWordlist; preferedListDictCode=english%3Benglish-japanese%3Benglish-korean; _gid=GA1.3.748680255.1563428131; username=sean+cai; pageView=1; glt_3_1Rly-IzDTFvKO75hiQQbkpInsqcVx6RBnqVUozkm1OVH_QRzS-xI3Cwj7qq7hWv5=st2.wOMIOmAAkpSfnDRcaOhul01tU3U.DjBDtlcZfb_r3dVxfXtQog.aUGIKz6CnjemtX-oMIVfxl2nuiY; remember-me=YWE5MmM5Zjk2ZmVmNDIyYjkwZjA0NWJlNzkwOWVmNGE6MTU2NDY0ODc2NzMwNTphMjgxNzRiMGJjODZiNGEzY2I5ZDQ5MGExMGM3ZWUzYg; JSESSIONID=D52BD27FFBB2FF92031D38FF4086D610-n1; _gat=1; pl_p=cdo-p20|cdo-p2|cdo-p13|cdo-23|cdo-21|cdo-p1";
    private static HttpURLConnection con;

    public String search(String word) {
        String url = "https://dictionary.cambridge.org/dictionary/english/" + word;
        try {
            URL myurl = new URL(url);
            con = (HttpURLConnection) myurl.openConnection();
            con.setRequestMethod("GET");
            con.addRequestProperty("Cookie", cookie);
            con.addRequestProperty("User-Agent", userAgent);
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String returnContent = null;
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()))) {
            String content_line;
            StringBuilder content = new StringBuilder();

            while ((content_line = in.readLine()) != null) {
                content.append(content_line);
                content.append(System.lineSeparator());
            }
            returnContent = content.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            con.disconnect();
        }
        return returnContent;
    }


    public boolean addToDictory(String word, String dictionaryID) {
        String url = "https://dictionary.cambridge.org/mydictionary/api/createWordlistEntry";
        try {
            URL myurl = new URL(url);
            con = (HttpURLConnection) myurl.openConnection();
            con.setRequestMethod("POST");
            con.addRequestProperty("Cookie", cookie);
            con.addRequestProperty("User-Agent", userAgent);
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        // 设置接收类型否则返回415错误
        //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
        con.setRequestProperty("accept", "application/json");
        // 往服务器里面发送数据
        WordList wordList = new WordList(word, dictionaryID);
        String Json = new Gson().toJson(wordList);
        System.out.println("JSON:" + Json);
        byte[] writebytes = Json.getBytes();
        // 设置文件长度
        con.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
        OutputStream outwritestream = null;
        try {
            outwritestream = con.getOutputStream();
            outwritestream.write(Json.getBytes());
            outwritestream.flush();
            outwritestream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (con.getResponseCode() == 200) {

                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public String extractSense(String content) {
        Document doc = Jsoup.parse(content);
        Elements links = doc.getElementsByClass("def-block pad-indent");
        if (links.size() > 0) {
            return links.get(0).attr("data-wl-senseid");
        }
        return null;
    }


    public static void main(String[] args) throws IOException {
        Dictionary dictionary = new Dictionary();
        String outFilePath = "C:\\Users\\sean\\Documents\\englishword\\src\\main\\resources\\out.txt";
        String line;
        try (BufferedReader reader = new BufferedReader(new FileReader(new File(outFilePath)))) {
            while ((line = reader.readLine()) != null) {
                System.out.println("查询单词：" + line);
                String html = dictionary.search(line);
                if (html != null) {
                    String senseId = dictionary.extractSense(html);
                    System.out.println("单词SenseId：" + senseId);
                    if (senseId != null) {
                        System.out.println("添加单词：" + line);
                        dictionary.addToDictory(senseId, "20550845");
                    }
                } else {
                    System.out.println("无法获取内容");
                }
            }
        }
    }
}
